﻿using Microsoft.EntityFrameworkCore;
using tju.cme.BookStore2024.webapi.Models.EF;
using tju.cme.BookStore2024.webapi.Models.ViewModels.Novel;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace tju.cme.BookStore2024.webapi.Services
{
    /// <summary>
    /// T031novel的相关服务
    /// </summary>
    /// <param name="context"></param>
    /// <param name="configuration"></param>
    public class NovelServices(BookStore2024Context context, IConfiguration configuration)
    {
        /// <summary>
        /// 获得所有小说
        /// </summary>
        /// <returns></returns>
        public async Task<IEnumerable<T031novel>> GetAllNovelsAsync()
        {
            
            return await context.T031novels.ToListAsync();
        }



        /// <summary>
        /// 根据小说类型获取小说
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public async Task<IEnumerable<T031novel>> GetNovelsByTypeAsync(string type)
        {
            return await context.T031novels.Where(m => m.Type == type).ToListAsync();
        }


        /// <summary>
        /// 获得所有上架到书城的小说
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public async Task<IEnumerable<T031novel>> GetOnShelfAsync()
        {
            return await context.T031novels.Where(m => m.OnShelf == true ).ToListAsync();
        }



        /// <summary>
        /// 根据作者id，返回该作者的所有小说
        /// </summary>
        /// <param name="authorId"></param>
        /// <returns></returns>
        public async Task<IEnumerable<T031novel>> GetNovelsByAuthorIdAsync(Guid authorId)
        {
            return await context.T031novels.Where(m => m.AuthorId == authorId).ToListAsync();
        }



        /// <summary>
        /// 根据管理员id,返回被其管理的所有小说和作者
        /// </summary>
        /// <param name="adminId"></param>
        /// <returns></returns>
        public async Task<IEnumerable<V031novelWith011Author>> GetNovelsByAdminIdAsync(Guid adminId)
        {
            return await context.V031novelWith011Authors
                .Where(m => m.AdministratorId == adminId)
                .ToListAsync();
        }


        /// <summary>
        /// 创建小说
        /// </summary>
        /// <param name="model"></param>
        /// <param name="authorId"></param>
        /// <returns></returns>
        public async Task CreateNovelAsync(NovelCreateModel model, Guid authorId)
        {
            if (model.Status != "Draft" && model.Status != "Submitted") throw new Exception("违规状态");
            var newItem = new T031novel()
            {
                Id = Guid.NewGuid(),
                NovelTitle = model.NovelTitle,
                AuthorId = authorId,
                NovelImageAddress=model.NovelImageAddress,
                UpdateToChapter=0,
                NovelTotalWords=0,
                Type = model.Type,
                Profile=model.Profile,
                NovelGenerateTime = DateTime.Now,
                Status = model.Status, //设置小说状态为草稿或提交至管理员
            };
            await context.T031novels.AddAsync(newItem);
            await context.SaveChangesAsync();
        }

        /// <summary>
        /// 小说提交至管理员审核
        /// </summary>
        /// <param name="novelId"></param>
        /// <returns></returns>
        public async Task UpToAdminAsync(Guid novelId,Guid authorId)
        {
            var novel = await context.T031novels.FirstOrDefaultAsync(m => m.Id == novelId && m.AuthorId == authorId);
            
            if (novel == null) throw new Exception("未找到该小说");

            if (novel.Status =="Draft")
            {
                novel.Status = "Submitted";
                await context.SaveChangesAsync();
            }
        }


        /// <summary>
        /// 管理员审核已提交的小说
        /// </summary>
        /// <param name="novelId"></param>
        /// <param name="adminId"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task ExamineNovelAsync(NovelExamineModel model, Guid adminId)
        {
            if (await IsAdminOfNovelAsync(adminId, model.Id)== false) throw new Exception("违规操作");

            var novel = await context.T031novels.FirstOrDefaultAsync(m => m.Id == model.Id);

            if (novel == null) throw new Exception("该小说不存在");

            if (novel.Status != "Submitted") throw new Exception("小说未提交或已审核");

            if (model.Status != "Approved" && model.Status != "Rejected") throw new Exception("审核状态设置违规");

            novel.Status = model.Status;
            await context.SaveChangesAsync();


        }

        /// <summary>
        /// 管理员将审核通过的小说上传到书城
        /// </summary>
        /// <param name="novelId"></param>
        /// <returns></returns>
        public async Task UpToBookStoreAsync(Guid novelId , Guid adminId)
        {
            if (!await IsAdminOfNovelAsync(adminId, novelId)) throw new Exception("违规操作");

            var novel = await context.T031novels.FirstOrDefaultAsync(m => m.Id == novelId);
            
            if (novel == null) throw new Exception("该小说不存在");
            
            else if (novel.Status == "Approved" && novel.NovelTotalWords >= 10)
            {
                novel.Status = "Published";
                await context.SaveChangesAsync();
            }
            else throw new Exception("无法上架");

        }

        /// <summary>
        /// 判断该管理员是否可以管理指定小说
        /// </summary>
        /// <param name="adminId"></param>
        /// <param name="novelId"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<bool> IsAdminOfNovelAsync(Guid adminId, Guid novelId)
        {
            var vnovel = await context.V011auWith031NoWith032ChWith022Admins
                .FirstOrDefaultAsync(nca => nca.NovelId == novelId);

            if (vnovel == null) throw new Exception("该小说不存在");

            return vnovel.AdminId == adminId;
        }


    }
}
